package com.doge.service.admin.user;

import com.alibaba.druid.util.StringUtils;
import com.doge.bean.base.BaseData;
import com.doge.bean.base.BaseParam;
import com.doge.bean.pojo.user.User;
import com.doge.bean.pojo.user.UserExample;
import com.doge.exception.Param402Exception;
import com.doge.mapper.UserMapper;
import com.doge.util.valid.ParamValidation;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.jsqlparser.util.validation.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: project2-wechat-mall
 * @description:
 * @author: zhu lei
 * @create: 2021-11-29 22:19
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    public User userListDetail(Integer id) throws Exception {

        if (id == null) {
            throw new Param402Exception("传入参数异常！");
        }
        UserExample userExample = new UserExample();
        userExample.createCriteria().andIdEqualTo(id);
        List<User> userList = userMapper.selectByExample(userExample);
        return userList.size() == 0 ? null : userList.get(0);
    }

    public BaseData userList(String username, String mobile, Integer id, BaseParam baseParam) throws Exception {
        if (!StringUtils.isEmpty(mobile) && !ParamValidation.phoneNumValId(mobile)) {
            throw new Param402Exception("号码格式是以“135、155、177、139、153、187为开头的11位数字”");
        }
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if (id != null) {
            criteria.andIdEqualTo(id);
        }
        if (!StringUtils.isEmpty(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (!StringUtils.isEmpty(mobile)) {
            criteria.andMobileLike("%" + mobile + "%");
        }
        userExample.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        List<User> users = userMapper.selectByExample(userExample);
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        long total = userPageInfo.getTotal();
        return BaseData.list(users, total);
    }

    public int updateList(User user) throws Exception {
        if (!ParamValidation.phoneNumValId(user.getMobile()))

            throw new Param402Exception("号码格式是以“135、155、177、139、153、187为开头的11位数字”");

        return userMapper.updateByPrimaryKeySelective(user);
    }
}